package fr.smile.sandbox.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.validation.BindException;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import fr.smile.sandbox.Product;
import fr.smile.sandbox.ProductDAO;
import fr.smile.sandbox.ProductService;

@SuppressWarnings("deprecation")
public class ProductUpdateController extends SimpleFormController {

	// private ProductService productService;

	public void setProductService(ProductService productService) {
		// this.productService = productService;
	}

	public ProductUpdateController() {
		setCommandClass(Product.class);
		setCommandName("product");
	}

	@Override
	protected Product formBackingObject(HttpServletRequest request)
			throws Exception {
		/* Récupération de l'ID passé en paramètre */
		long id = Long.parseLong(request.getParameter("id"));
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		ProductDAO myProduct = (ProductDAO) context.getBean("productDAO");
		Product product = myProduct.getProductByID(id);
		return product;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		System.out.println("Sauvegarde");
		Product product = (Product) command;

		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		ProductDAO myProduct = (ProductDAO) context.getBean("productDAO");
		myProduct.saveProduct(product);
		return new ModelAndView("redirect:list.html");
	}

}
